using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace TXLooker.UI
{
    internal class CheckBoxListItemWrapper<T>
        where T : class
    {
        public static Type ItemType
        {
            get
            {
                if( m_type == null )
                {
                    Type type = typeof(T);
                    lock(type) { if( m_type == null ) m_type = type; }
                }
                return m_type;
            }
        }
        private static Type m_type = null;

        public CheckBoxListItemWrapper( T item, string propertyName )
        {
            this.Item = item;
            this.PropertyName = propertyName;
        }

        public T Item
        {
            get { return this.m_item; }
            internal set
            {
                if( object.ReferenceEquals( value, null ) )
                    throw new ArgumentException();

                this.m_item = value;
            }
        }
        private T m_item = default( T );

        public string PropertyName
        {
            get { return this.m_propertyName; }
            internal set
            {
                if( string.IsNullOrEmpty( value ) )
                    throw new Exception();

                this.m_propertyName = value;
            }
        }
        private string m_propertyName = null;

        public override string ToString()
        {
            //first try to get property
            MemberInfo[] members = ItemType.GetMember( this.PropertyName );

            object value = null;

            foreach( MemberInfo m in members )
            {
                switch( m.MemberType )
                {
                    case MemberTypes.Property:
                        value = ItemType.GetProperty(this.PropertyName).GetValue( this.Item, null );
                        break;
                    case MemberTypes.Field:
                        value = ItemType.GetField(this.PropertyName).GetValue(this.Item);
                        break;
                    default:
                        continue;
                }

                if( value != null ) break;
            }

            return value != null ? value.ToString() : string.Empty;
        }
    }
}
